
import { MENU_TYPE, SESSION_KEY } from '@/utils/constants'

// 将路由菜单存储至session
export const setCacheRouter = (routers) => {
  sessionStorage.setItem(SESSION_KEY.ROUTER, JSON.stringify(routers))
}

// 从session中获取路由菜单
export const getCacheRouter = () => {
  const routerMenu = sessionStorage.getItem(SESSION_KEY.ROUTER);
  if (routerMenu) {
    return JSON.parse(routerMenu);
  }
  return routerMenu;
}

// 移除session中的路由菜单
export const clearCacheRouter = () => {
  sessionStorage.removeItem(SESSION_KEY.ROUTER)
}

// 将页面菜单存储至session
export const setCacheInnerMenu = (innerMenus) => {
  sessionStorage.setItem(SESSION_KEY.INNER_MENU, JSON.stringify(innerMenus))
}

// 从session中获取页面内菜单
export const getCacheInnerMenu = (menuId) => {
  const routerMenu = sessionStorage.getItem(SESSION_KEY.INNER_MENU);
  if (routerMenu) {
    const innerMenus = JSON.parse(routerMenu);
    for (let item in innerMenus) {
      if (item == menuId) {
        return innerMenus[item];
      }
    }
    return null;
  }
  return routerMenu;
}

// 移除session中的路由菜单
export const clearCacheInnerMenu = () => {
  sessionStorage.removeItem(SESSION_KEY.INNER_MENU)
}

export const convertMenuToRouter = (menus) => {
  if (!menus || menus.length === 0) return null;
  const tmpMenuIds = [];
  menus.forEach(menu => {
    tmpMenuIds.push(menu.id);
  })

  // 得到所有父菜单
  const routers = [];
  for (let i = 0; i < menus.length; i++) {
    // 递归封装所有子菜单
    if (tmpMenuIds.indexOf(menus[i].parentId) == -1) {
      const router = setRouteData(menus[i]);
      packageChildMenu(router, menus);
      routers.push(router);
    }
  }
  return routers;
}

export const packageChildMenu = (parentMenu, menus) => {
  if (parentMenu == null || menus == null || menus.length === 0)
    return;

  menus.forEach(menu => {
    if (menu.parentId === parentMenu.id) {
      const router = setRouteData(menu);
      packageChildMenu(menu, menus);
      parentMenu.children.push(router);
    }
  })
}

/**
 * 将后端返回的菜单数据封装成路由需要的格式
 * 
 * @param {object} route 后端菜单对象
 */
export const setRouteData = (route) => {
  let routeData = {
    meta: {},
    children: []
  }
  routeData.id = route.id;
  routeData.path = route.clientUri;
  routeData.name = route.name;
  //routeData.component = () => import(`@${route.clientPath}`);
  routeData.component = path2Component(route.clientPath)
  routeData.meta.title = route.menuMeta.title;
  routeData.meta.icon = route.menuMeta.icon;
  routeData.meta.id = route.id;

  return routeData;
}

/**
 * 将服务器的组件路径占转换为vue需要的函数对象
 * 
 * @param {function} path 
 */
export const path2Component = (path) => {
  return path.indexOf('layout') != -1 ? () => import('@/layout/index.vue')
    : resolve => require([`@/views${path}`], resolve);
}